#!/bin/bash

sqlitedb="/usr/lib64/nagios/plugins/SiteJobMon/remotemon.db"
updatejobstatinsqlite(){
    site=$1
    pool=$2
    jobid=$3
    jobstat=$4
    sqlite3 $sqlitedb "update samjobtask set jobstat=$jobstat where jobid=${jobid} and site='$site' and pool='$pool'" 
}
datetime=`date +%s`
export _condor_SEC_CLIENT_AUTHENTICATION_METHODS=CLAIMTOBE
sqlite3 $sqlitedb "delete from samjobtask where strftime('%s','now')-subtime > datavailtime"
for line in `sqlite3 $sqlitedb "select site,pool,jobid,jobstat from samjobtask where jobstat!=4 and jobstat!=100"`
do
  echo $line
  site_schedd=${line%%|*}
  infoother=${line#*|}
  site_cm=${infoother%%|*}
  infoother=${infoother#*|}
  job_id=${infoother%%|*}
  dbjobstat=${infoother#*|}
  logger "/usr/bin/condor_q ${job_id} -af jobstatus -name ${site_schedd} -pool ${site_cm}"
  jobstat=`/usr/bin/condor_q ${job_id} -af jobstatus -name ${site_schedd} -pool ${site_cm}`
  sitemonmsg="$0 sitesched:${site_schedd} sitecm:${site_cm} jobid:$job_id jobstat:$jobstat tm:$datetime"
  logger $sitemonmsg
  if [ $jobstat != $dbjobstat ];then
    updatejobstatinsqlite ${site_schedd} ${site_cm} ${job_id} $jobstat
  fi
done
for line in `sqlite3 $sqlitedb "select site,pool,jobid,jobstat from samjobtask where jobstat!=4 and jobstat!=100 and jobstat!=101 and strftime('%s','now')-subtime > jobvaildtime"`
do
  echo $line
  site_schedd=${line%%|*}
  infoother=${line#*|}
  site_cm=${infoother%%|*}
  infoother=${infoother#*|}
  job_id=${infoother%%|*}
  dbjobstat=${infoother#*|}
  jobstat=101
  sitemonmsg="$0 sitesched:${site_schedd} sitecm:${site_cm} jobid:$job_id jobstat:$jobstat tm:$datetime"
  logger $sitemonmsg
  if [ $jobstat != $dbjobstat ];then
    updatejobstatinsqlite ${site_schedd} ${site_cm} ${job_id} $jobstat
  fi
done
